package com.jy.api.domain;

import com.aliyun.mns.client.CloudQueue;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.model.Message;
import com.jy.api.dao.RewardDao;
import com.jy.api.service.PaymentService;
import com.jy.api.signUpReq.web.WebCancelPayReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Profile;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * Created by lihu on 2017/12/29.
 */
@Component
@Profile("!dev")
@Slf4j
public class AliyunMNSConsume {
    private MNSClient client;

    private String cloudQueue;

    private PaymentService paymentService;

    @Autowired
    private RewardDao rewardDao;

    @EventListener(ApplicationReadyEvent.class)

    public void process() {
        CloudQueue queue = client.getQueueRef(cloudQueue);
        while (true) {
            log.info("Start to poll MNS message...");
            try {
                Message popMsg = queue.popMessage(2);
                if (popMsg != null) {
                    String[] s = popMsg.getMessageBody().split(":");
                    if (s[0].equals("refund")) {
                        // 退款结果查询
                        SwiftPassRefundQueryResult result = paymentService.queryRefundResult(s[1]);
                        if (result.isProcessing()) {
                            continue;
                        } else {
                            if (result.isSuccess()) {
                                log.debug("Succeed to refund order: {}", result.getOutRefundNo());
                                paymentService.callbackForThirdPartyRefundSuccess(result);
                            } else {
                                paymentService.callbackForThirdPartyRefundFail(result);
                            }

                            queue.deleteMessage(popMsg.getReceiptHandle());
                        }
                    } else {
                        // 支付结果查询
                        String orderId = popMsg.getMessageBody();

                        int dequeueCount = popMsg.getDequeueCount();

                        if (dequeueCount > 50) {
                            WebCancelPayReq req =new WebCancelPayReq();
                            SwiftPassReversePaymentResult reverseResult = paymentService.cancelThirdPartyPayment(orderId,req);
                            if (reverseResult.isSuccess()) {
                                queue.deleteMessage(popMsg.getReceiptHandle());
                            }
                        } else {
                            SwiftPassPaymentQueryBaseResult result = paymentService.queryMicroPay(orderId);
                            if (!result.isNeedQuery()) {
                                if (result.isSuccess()) {
                                    paymentService.callbackForMicroPaymentSuccess(result);
                                } else {
                                    paymentService.callbackForMicroPaymentFailed(orderId, result);
                                }
                                queue.deleteMessage(popMsg.getReceiptHandle());
                            }
                        }


                    }
                }
            } catch (Exception e) {
                log.error("Fail to process MNS message.", e);
            }
        }
    }

    @Autowired
    public void setClient(MNSClient client) {
        this.client = client;
    }

    @Autowired
    public void setPaymentService(PaymentService paymentService) {
        this.paymentService = paymentService;
    }

    @Value("${mns.cloud-queue}")
    public void setCloudQueue(String cloudQueue) {
        this.cloudQueue = cloudQueue;
    }
}
